<?php

declare(strict_types=1);

namespace app\middleware;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Cache;

class CheckToken
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $request->header("Authorization");
        if (!$token) {
            return error("请先登录", null, 501);
        }
        try {
            // 验证token
            $key = 'dkfjkldfjkl';
            $decoded = JWT::decode($token, new Key($key, 'HS256'));

            // 检查token是否在缓存中
            $cachedToken = Cache::get('token_' . $decoded->uid);
            if (!$cachedToken || $cachedToken !== $token) {
                return json(['code' => 501, 'msg' => '登录已过期']);
            }

            // 将用户信息注入到请求中，在控制器或其他地方可以直接通过 $request->uid 获取当前登录用户的ID
            $request->uid = $decoded->uid;
            $request->token = $token;

            // 添加调试信息
            trace('Token解析结果：' . json_encode([
                'uid' => $decoded->uid,
                'token' => $token,
                'request_uid' => $request->uid,
                'request_token' => $request->token
            ]), 'debug');


            return $next($request);
        } catch (\Exception $e) {
            return json(['code' => 501, 'msg' => '无效的token']);
        }
    }
}
